package com.hm.PushCaseService.service.captcha;

import com.hm.PushCaseService.pojo.response.CaptchaResponse;
import com.hm.PushCaseService.utils.captcha.CaptchaGenerator;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.UUID;

@Service
public class CaptchaService implements ICaptchaService {

    @Qualifier("jedisPool")
    private final JedisPool jedisPool;

    public CaptchaService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public CaptchaResponse getCaptcha() {
        //try块退出时，会自动调用res.close()方法，关闭资源。
        try (Jedis jedis = jedisPool.getResource()) {
            SpecCaptcha specCaptcha = CaptchaGenerator.getSpecCaptcha();
            //验证码结果
            String captcha = specCaptcha.text().toLowerCase();
            String imgBase64 = specCaptcha.toBase64("");
            String captchaKey = UUID.randomUUID().toString();
            //设置保存时间为60秒
            jedis.setex(captchaKey, 60, captcha);
            //生成bean
            CaptchaResponse captchaResponse = new CaptchaResponse();
            captchaResponse.imgBase64 = imgBase64;
            captchaResponse.captchaKey = captchaKey;
            return captchaResponse;
        }
    }

    @Override
    public HashMap<String, String> verify(String captcha, String captchaKey) {
        HashMap<String, String> resMap = new HashMap<>();
        try (Jedis jedis = jedisPool.getResource()) {
            //验证码
            boolean exists = jedis.exists(captchaKey);
            if (exists) {
                //说明有缓存
                String s = jedis.get(captchaKey);
                if (s.equals(captcha)) {
                    //验证码输入正确
                    resMap.put("state", "000");
                    resMap.put("msg", "成功！");
                } else {
                    //验证码输入错误
                    resMap.put("state", "002");
                    resMap.put("msg", "验证码错误！");
                }
            } else {
                //验证码失效
                resMap.put("state", "001");
                resMap.put("msg", "验证码已失效！");
            }
        }
        return resMap;
    }
}
